package cn.fan.minio.web;


import cn.fan.minio.config.MinIOConfig;
import io.minio.*;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件上传  返回的地址如果是图片可以直接预览  文件就会下载    前提是minio创建的buck 添加访问策略
 * 名字相同会覆盖（可以采用名字存一张文件表，存入minio为随机名）
 */
@Slf4j
@Component
public class FileManager {
    @Autowired
    private MinIOConfig minIOConfig;

    /**
     * 上传文件到MinIO
     *
     * @param file
     * @throws NoSuchAlgorithmException
     * @throws IOException
     * @throws InvalidKeyException
     */
    public String uploadFile(MultipartFile file) {
        try {
            MinioClient minioClient = buildMinioClient();
            Date date=new Date();
            System.out.println(date);
            SimpleDateFormat sdf1=new SimpleDateFormat("_yyyyMMddHHmmss_");
            String format1=sdf1.format(date)+file.getOriginalFilename();

            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(format1)
                    .contentType(file.getContentType())
                    .stream(file.getInputStream(), file.getSize(), -1)  // partSize -1表示整体(不分片)上传
                    .bucket(minIOConfig.getBucket())
                    .build();
            minioClient.putObject(putObjectArgs);
            StringBuilder sbPhotoPath = new StringBuilder(minIOConfig.getReadPath());
            sbPhotoPath.append("/").append(minIOConfig.getBucket()).append("/").append(format1);
//            http://192.168.14.55:9000/lkd/暴风截图20181024541843765.jpg
            return sbPhotoPath.toString();
        } catch (Exception ex) {
            log.error("minio put file error.", ex);
            throw new RuntimeException("上传文件失败");
        }
    }

    public InputStream downLoad(String fileName, HttpServletResponse response) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        InputStream inputStream = null;
        MinioClient minioClient = buildMinioClient();
        String[] split = fileName.split("/");
        String filename = split[split.length - 1];
        return minioClient.getObject(GetObjectArgs.builder().bucket(minIOConfig.getBucket()).object(filename).build());
    }

    public void delete(String fileName) {
        MinioClient minioClient = buildMinioClient();
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(minIOConfig.getBucket()).object(fileName).build());

        } catch (Exception ex) {
            log.error("minio put file error.", ex);
            throw new RuntimeException("删除文件失败");
        }

    }

    private MinioClient buildMinioClient() {
        return MinioClient
                .builder()
                .credentials(minIOConfig.getAccessKey(), minIOConfig.getSecretKey())
                .endpoint(minIOConfig.getEndpoint())
                .build();
    }
}
